import React, { memo, useState, useCallback, useMemo, useEffect } from 'react';
import { Modal, Steps, Upload, Button, Radio } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx/xlsx.mjs';


function jsonParse(str: string, defRtn?: any) {
  try {
    return JSON.parse(str);
  } catch (error) {
    return defRtn;
  }
}

const modalBodyStyle = {
  display: 'flex',
  flexDirection: 'column' as any,
  maxHeight: '500px'
};

interface IProps {
  visible: boolean;
  onCancel?(): void;
  onOK(data: any[], type: string): void;
  columns?: any[];
  importServer?: Function;
  apiDataFun?: Function;
  fromRow?: number;
  exportDataFun?: (list: any[]) => void;
}

export default memo(({ visible, onCancel, onOK, fromRow, exportDataFun, apiDataFun }: IProps) => {

  const [dataSource, setDataSource] = useState([]);
  const [value, setValue] = useState('update');

  const [fileName, setFileName] = useState('');

  const beforeUpload = useCallback(
    (file) => {
      window.$app.showLoading();
      const reader = new FileReader();
      setFileName(file.name);
      reader.onload = async (e: any) => {
        console.log('onload');
        window.$app.hideLoading();
        const data = e.target.result;
        const wb = XLSX.read(data, { type: 'binary' });
        const worksheet = JSON.stringify(
          XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { range: fromRow || 0 })
        );
        let dataSource = jsonParse(worksheet);
        dataSource = exportDataFun?.(dataSource) || dataSource; // 直接当前对象 有需要的话处理数据展示格式
        if (apiDataFun) {
          dataSource = await apiDataFun(dataSource);
        }
        if (dataSource.length > 0) dataSource.splice(0, 1);
        setDataSource(dataSource);
      };
      reader.readAsBinaryString(file);
      return false;
    },
    [exportDataFun, apiDataFun]
  );

  const onComplete = useCallback(() => {
    setFileName('');
    onCancel?.();
    setDataSource([]);
  }, [onCancel]);

  const onOk = () => {
    setFileName('');
    setDataSource([]);
    onOK(dataSource, value);
  };

  return (
    <Modal
      onCancel={onComplete}
      onOk={onOk}
      maskClosable={false}
      visible={visible}
      destroyOnClose
      width={900}
      title={window.$app.t('数据导入')}
      bodyStyle={modalBodyStyle}
    >

      <span className="whiteSpace" />
      <Upload.Dragger accept=".xlsx,.xls" beforeUpload={beforeUpload} showUploadList={false}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        {
          fileName ? <p className="ant-upload-text">{fileName}</p> : <>
            <p className="ant-upload-text">{window.$app.t('选择文件或拖动文件进行上传')}</p>
            <p className="ant-upload-hint">{window.$app.t('支持格式：.xlsx .xls,上传大小无限制')}</p></>
        }
      </Upload.Dragger>
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: '32px', }}>
        <span style={{ marginRight: '16px' }}>{window.$app.t('重复数据处理方式')}</span>
        <Radio.Group onChange={(e) => setValue(e.target.value)} value={value}>
          <Radio value={'update'}>{window.$app.t('更新')}</Radio>
          <Radio value={'skip'}>{window.$app.t('跳过')}</Radio>
        </Radio.Group>
      </div>

    </Modal>
  );
});
